package com.atnjupt.service.impl;

import com.atnjupt.bean.*;
import com.atnjupt.dao.impl.OrderDaoImpl;
import com.atnjupt.dao.impl.OrderItemDaoImpl;
import com.atnjupt.service.BookService;
import com.atnjupt.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @author Wizarder
 * @create 2021-06-11 16:16
 */
public class OrderServiceImpl implements OrderService {
    private OrderDaoImpl orderDao = new OrderDaoImpl();
    private OrderItemDaoImpl orderItemDao = new OrderItemDaoImpl();
    private BookService bookService = new BookServiceImpl();
    @Override
    public String createOrder(Cart cart, Integer userID) {
        //创建订单号,唯一性
        String orderId = System.currentTimeMillis() + "" + userID;
        //创建订单对象
        Order order = new Order(orderId,new Date(),cart.getTotalPrice(),0,userID);
        orderDao.saveOrder(order);
        //遍历购物车的商品项，就是订单项
        Map<Integer, CartItem> items = cart.getItems();
        int i = 5/0;
        for (Map.Entry<Integer, CartItem> entry: items.entrySet()){
            //获取商品项目
            CartItem cartItem  = entry.getValue();
            //把商品项目转成OrderItem项
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),
                    cartItem.getTotalPrice(),orderId);
            //保存到数据库中
            orderItemDao.saveOderItem(orderItem);
            //查询到对应的Book对象,修改库存和销量
            Book book = bookService.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookService.updateBook(book);

        }
        //保存完后购物车需要请空
        cart.clear();
        return orderId;
    }
}
